const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");

var cors = require("koa2-cors");

const index = require("./routes/index");
const che = require("./routes/che");
const mono = require("./routes/mono");
const che_gps = require("./routes/che-gps");

// error handler
onerror(app);

// middlewares
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
);
app.use(cors());
app.use(json());
app.use(logger());
app.use(require("koa-static")(__dirname + "/public"));

app.use(
  views(__dirname + "/views", {
    extension: "ejs",
  })
);

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

async function checkUserPermission(ctx) {
  return true;

  //如果是白名单,则直接过
  const whiteJson = require("./auth/white.json");

  var is_white = false;
  if (whiteJson.hasOwnProperty(ctx.path)) {
    is_white = true;
  }

  console.log(ctx, "============ctx===========");

  var token =
    ctx.request.query["token"] ||
    ctx.request.body["token"] ||
    ctx.header["token"] ||
    "";

  if (token.length == 0 && !is_white) {
    return false;
  }

  //如果有token就把用户信息带上
  const redisMap = require("./auth/redis.json");

  if (redisMap.hasOwnProperty(token)) {
    ctx.request.body.token_user = redisMap[token];
    return true;
  } else {
    if (is_white) {
      return true;
    }
    return false;
  }
}

// app.use(async (ctx, next) => {
//     if (await checkUserPermission(ctx)) {
//         await next();
//     } else {
//         ctx.body = {
//             success: false,
//             code: 4001,
//             message: 'token缺失或过期'
//         };
//     }
// });

// routes
app.use(index.routes(), index.allowedMethods());
app.use(che.routes(), che.allowedMethods());
app.use(mono.routes(), che.allowedMethods());
app.use(che_gps.routes(), che_gps.allowedMethods());



// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = app;
